package com.sprint.questai.ocrhttp;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileService {

    private final Path uploadDir;

    public FileService() {
        // 将路径设置为 src/main/resources/uploads
        uploadDir = Paths.get("src", "main", "resources", "uploads");
        try {
            // 如果 uploads 目录不存在，创建该目录
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }
        } catch (IOException e) {
            throw new RuntimeException("Could not create upload directory!", e);
        }
    }

    public String storeFile(MultipartFile file) {
        // 生成唯一的文件ID，并创建文件路径
        String fileId = UUID.randomUUID().toString();
        Path filePath = uploadDir.resolve(fileId + "-" + file.getOriginalFilename());

        try {
            // 将文件复制到目标位置，如果已存在则替换
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            // 记录错误并抛出自定义异常
            // log.error("Failed to store file", e);
            throw new RuntimeException("Failed to store file", e);
        }

        // 返回文件路径
        return filePath.toString();
    }
}
